<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/5/18 0018
 * Time: 上午 10:46
 */
class myformHelper
{

    public  $model;
    private $fileds;
    private $error;
    private $jscript;
    private $jsDateKeys;
    private $formAction;

    public function __construct($model,$formAction)
    {
        $this->model = $model;
        $this->formAction = $formAction;
    }

    private function createItem($key)
    {
        $rule = $this->model->getRule($key);
        if (empty($rule))
        {
            return null;
        }
        $input = $this->createInput($key, $rule);
        if (empty($input))
        {
            return;
        }
        $html = '<div class="form-group">' . $this->createLabel($rule['label']);
        $html .= $input;
        $html .= '</div>';
        if ($rule['type'] == 'file')
        {
            $html .= $this->createPicShow($rule);
        }
        return $html;
    }

    private function addJScript($script)
    {
        $this->jscript .= $script;
    }

    private function addJsDateKeys($key)
    {
        $this->jsDateKeys[] = $key;
    }

    private function createPicShow($rule)
    {
        $html = '<div class="form-group" id="' . $rule['file']['picShowId'] . '" ';
        $html .= (empty($rule['value']) ? ' style="display:none;"' : '') . '>';
        $html .= '<div class="label"><label></label></div>';
        $html .= '<div class="field"><img src="' . $rule['value'] . '" style="' . $rule['file']['picStyle'] . '" /></div></div>';
        $this->addJScript('initUploadPic("' . $rule['file']['buttonId'] . '","' . $rule['file']['id'] . '","' . $rule['file']['picShowId'] . '");');
        return $html;
    }

    private function createLabel($label)
    {
        $label = empty($label) ? '' : $label . '：';
        return '<div class="label"><label>' . $label . '</label></div>';
    }

    private function createInput($key, $rule)
    {
        if (empty($rule))
        {
            return null;
        }
        $html = '<div class="field">';
        if ($rule['type'] == 'text')
        {
            $html .= '<input type="text" name="' . $key . '" class="input ' . $rule['inputClass'] . '" value="' . $rule['value'] . '"';
            $html .= (isset($rule['inputId']) && !empty($rule['inputId'])) ? ' id="'.$rule['inputId'].'"' : '';
            $html .= $rule['editable'] ? '' : ' readonly="readonly"';
            $html .= ' placeholder="' . $rule['placeholder'] . '"';
            $html .= ' data-validate="' . $rule['validate'] . '" style="' . $rule['style'] . '"/>';
        }
        else if($rule['type'] == 'date')
        {
            $html .= '<input type="text" name="' . $key . '" class="input ' . $rule['inputClass'] . '" value="' . $rule['value'] . '"';
            $html .= (isset($rule['inputId']) && !empty($rule['inputId'])) ? ' id="'.$rule['inputId'].'"' : '';
            $html .=  ' readonly="readonly"';
            $html .= ' placeholder="' . $rule['placeholder'] . '"';
            $html .= ' data-validate="' . $rule['validate'] . '" style="' . $rule['style'] . '"/>';
            $this->addJsDateKeys($key);
        }
        else if ($rule['type'] == 'radio')
        {
            if (!isset($rule['radio']) || count($rule['radio']) < 1)
            {
                return null;
            }
            $html .= '<div class="button-group radio">';
            foreach ($rule['radio'] as $v)
            {
                $checked = $v['value'] == $rule['value'];
                $checkStr = $checked ? 'checked="checked"' : '';
                $html .= '<label class="button ' . ($checked ? 'active' : '') . '">';
                $html .= '<input name="' . $key . '" value="' . $v['value'] . '" ' . $checkStr . '  data-validate="' . $rule['validate'] . '" type="radio"  style="' . $rule['style'] . '">';
                $html .= '<span class="icon icon-check"></span> ' . $v['label'] . '</label>';
            }
            $html .= '</div>';
        }
        else if ($rule['type'] == 'textarea')
        {
            $html .= '<textarea name="' . $key . '" class="input ' . $rule['inputClass'] . '" style="' . $rule['style'] . '"';
            $html .= ' placeholder="' . $rule['placeholder'] . '"';
            $html .= (isset($rule['inputId']) && !empty($rule['inputId'])) ? ' id="'.$rule['inputId'].'"' : '';
            $html .= $rule['editable'] ? '' : ' readonly="readonly"';
            $html .= ' data-validate="' . $rule['validate'] . '" />' . $rule['value'] . '</textarea>';
        }
        else if ($rule['type'] == 'file')
        {
            if (!isset($rule['file']))
            {
                return null;
            }
            $f = $rule['file'];
            $html .= '<input type="button" class="button bg-blue margin-left" id="' . $f['buttonId'] . '"';
            $html .= ' value="' . $f['buttonLabel'] . '"  style="float:left;margin-left:0px">';
            $html .= '<input type="file" id="' . $f['id'] . '" name="' . $f['name'] . '" style="display: none;" data-validate="' . $rule['validate'] . '" >';
            $html .= '<div class="tipss">' . $f['tipss'] . '</div>';
        }
        $html .= '<div class="tips"></div></div>';
        return $html;
    }

    private function createSubmit($v)
    {
        $html = '<div class="form-group"><div class="label"><label></label></div><div class="field">';
        $html .= '<button class="button bg-main icon-check-square-o" type="submit"> ' . $v . '</button></div></div>';
        return $html;
    }

    public function createForm()
    {
        $this->jscript = '';
        $this->jsDateKeys = array();
        $keys = $this->model->allKeys();
        $html = '<form method="post" class="form-x" action="'.$this->formAction.'" enctype="multipart/form-data">';
        foreach ($keys as $k)
        {
            $html .= $this->createItem($k);
        }
        $html .= $this->createSubmit($this->model->formbutton);
        $html .= '</form>';
        return $html;
    }

    public function showForm()
    {
        echo $this->createFrom();
    }

    public function createScript()
    {
        if(!empty($this->jsDateKeys))
        {
            $initStr = '';
            $clickStr = '';
            foreach($this->jsDateKeys as $k)
            {
                if(isset($this->model->rules[$k]) && $this->model->rules[$k]['type'] == 'date')
                {
                    $initStr .= 'J(\'#startAt\').calendar({ format:\''.$this->model->rules[$k]['date']['format'].'\' });';
                    $clickStr .= '$(\'#'.$this->model->rules[$k]['inputId'].'\').click(function(){J.calendar.Show();});';
                }
            }
            if(!empty($initStr))
            {
                $initStr =  'J(function(){'.$initStr.'});';
            }
            $this->addJScript($initStr.$clickStr);
        }
        if(!empty($this->jscript))
        {
            return '<script>'.$this->jscript.'</script>';
        }
        return '';
    }

    public function showScript()
    {
        echo $this->createScript();
    }



    public function filedsData()
    {
        return $this->fileds;
    }

    /**
     * 从表单中读取数据
     */
    public function loadAndValidateFormData()
    {
        $this->fileds = array();
        $keys = $this->model->allKeys();
        foreach ($keys as $k)
        {
            $rule = $this->model->getRule($k);
            if (empty($rule))
            {
                continue;
            }
            if ($rule['type'] == 'file')
            {
                $f = $rule['file'];
                $error = true;
                if(!isset($_FILES[$f['name']]) || $_FILES[$f['name']]['size'] < 10)
                {
                    $error = $this->model->validate('',$k);
                }
                else if ($_FILES[$f['name']]['size'] > $f['maxSize'])
                {
                    $error = '图片大小不能超过2M';
                }
                else
                {
                    $error = $this->model->validate($_FILES[$f['name']],$k);
                }
                //图片上传
                if($error === true)
                {
                    require_once(LIB_PATH . "image/myuploadimg.php");
                    $myuploadimg = new myuploadimg($f['name'], WEB_PATH . 'assets/'.$f['uploadpath'], myHelper::createFileName());
                    $path = $myuploadimg->uploads();
                    if ($path === false)
                    {
                        return $myuploadimg->GetFileerror();
                    }
                    else
                    {
                        if (!copy($path, FRONT_WEB_PATH . substr($path, strlen(WEB_PATH))))
                        {
                            return '照片上传失败';
                        }
                        else
                        {
                            $path = substr($path, strlen(WEB_PATH));
                            $this->fileds[$k] = $path;
                        }
                    }
                }
                else if($error == 'unset')
                {
                    continue;
                }
                else
                {
                    return $error;
                }
            }
            else
            {
                $filed = trim(myrequest::p($k, ''));
                $error = $this->model->validate($filed,$k);
                if($error === true)
                {
                    if($rule['keysWithTable'])
                    {
                        $this->fileds[$k] = $filed;
                    }
                }
                else if($error == 'unset')
                {
                    continue;
                }
                else
                {
                    return $error;
                }
            }
        }
        return true;
    }


}